package com.test.mooan.labama.utils_boom.http_boom;

import static com.test.mooan.labama.activity_fragment_boom.base_boom.BaseLnActivity_boom.hasShowStarDalog;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseApplication_boom;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseLnActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.CountryInfo_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.UrlInfo_boom;
import com.test.mooan.labama.constants_boom.Constant_boom;
import com.test.mooan.labama.constants_boom.Url_boom;
import com.test.mooan.labama.demo.Demo;
import com.test.mooan.labama.utils_boom.Stringutil_boom;
import com.test.mooan.labama.utils_boom.Threadutils_boom;
import com.test.mooan.labama.utils_boom.analytics_boom.util_boom.AnalyticsUtil_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


public class HttpManager_boom {

    public static String Upload_Info_Url = "";

    private HttpManager_boom() {

        //tag2025
        mHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        mClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(mHttpLoggingInterceptor)
                .addInterceptor(new ReqInterceptor_boom())
                .callTimeout(999000, TimeUnit.MILLISECONDS)
                .connectTimeout(99000, TimeUnit.MILLISECONDS)
                .readTimeout(99000, TimeUnit.MILLISECONDS)
                .writeTimeout(99000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static class Inner {
        private static final HttpManager_boom instance = new HttpManager_boom();
    }

    public static HttpManager_boom getInstance() {
        return Inner.instance;
    }

    private static OkHttpClient mClient;

    private static final HttpLoggingInterceptor mHttpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLogger_boom());

    //请求响应回调
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            HttpPresenter_boom.getInstance().showToastOnUiThread("Request Fail");
            Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogDismiss());
            Log.e("Http Response", "Request Fail");
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String body = Objects.requireNonNull(response.body()).string();
            String request = Objects.requireNonNull(call.request().body()).toString();
            Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogDismiss());
            try {
                String word = Stringutil_boom.getUrlSuffix(response.request().url().toString());
                JSONObject requestJo = null;
                if (request.startsWith("{") && request.endsWith("}"))
                    requestJo = new JSONObject(request);
                handleResponse(word, new JSONObject(body), requestJo);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    //处理响应
    private void handleResponse(String lastWord, JSONObject responseJson, JSONObject requestJson) {
        Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().notifyActivityHandleResponse(lastWord, responseJson, requestJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson() {
        return getRequestJson(new JSONObject(), "", "");
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson(String product, String token) {
        return getRequestJson(new JSONObject(), product, token);
    }

    private JSONObject getRequestJson(JSONObject jsonObject) {
        return getRequestJson(jsonObject, "", "");
    }

    private JSONObject getRequestJson(JSONObject jsonObject, String product, String token) {

        if (TextUtils.isEmpty(product)) product = Constant_boom.PRODUCT;
        if (TextUtils.isEmpty(token)) token = UserInfoHelper_boom.gInstance().gToken();

        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_boom.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_boom.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_boom.INSTANCE.getAndroidId());
            jsonObject.put("version", Constant_boom.APP_VERSION.trim());
            jsonObject.put("token", token.trim());
            jsonObject.put("androidId", AnalyticsUtil_boom.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_boom.gInstance().gUserId().trim());
            jsonObject.put("advertId", AnalyticsUtil_boom.INSTANCE.getAdId());
            jsonObject.put("product", product.trim());
            jsonObject.put("clientType", Constant_boom.CLIENT.trim());
            jsonObject.put("apiVersion", "v3");
            jsonObject.put("localTimestamp",String.valueOf(System.currentTimeMillis()));
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;

    }

    //发送请求
    public void request(String lastWord, String jsonString) {
        requestWithoutCountryPrefix(CountryInfo_boom.gInstance().gFront() + lastWord, jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix(String lastWord, String jsonString) {

        if (TextUtils.isEmpty(jsonString)) jsonString = "{}";

        final String fJsonString = jsonString;

        Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogShow());
        Threadutils_boom.getInstance().runOnChildThread(() -> {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            Request request = new Request.Builder()
                    .url(CountryInfo_boom.gInstance().gBaseUrl() + lastWord)
                    .header("product", Constant_boom.PRODUCT)
                    .post(RequestBody.Companion.create(fJsonString, mediaType))
                    .build();
            Call call = mClient.newCall(request);
            call.enqueue(callback);
        });
    }

    public void requestForDevice(String lastWord, String jsonString) {

        final String lastWord1 = CountryInfo_boom.gInstance().gFront() + lastWord;

        if (TextUtils.isEmpty(jsonString)) jsonString = "{}";

        final String fJsonString = jsonString;

        Threadutils_boom.getInstance().runOnChildThread(() -> {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            Request request = new Request.Builder()
                    .url(CountryInfo_boom.gInstance().gBaseUrl() + lastWord1)
                    .header("product", Constant_boom.PRODUCT)
                    .post(RequestBody.Companion.create(fJsonString, mediaType))
                    .build();
            Call call = mClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {}
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {}
            });
        });
    }

    /**
     * 获取Url
     */
    public void requestUrls() {
        request(Url_boom.PATH_REQUEST_URLS, getRequestJson().toString());
    }

    //获取App配置
    public void getAppShowInfo() {
        request(Url_boom.PATH_APP_SHOW_INFO, getRequestJson().toString());
    }

    //注册登录-无验证码
    public void userLoginNoCode(String phoneNum) {
        UserInfoHelper_boom.gInstance().sMobile(Stringutil_boom.getSafeString(phoneNum));
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_boom.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_boom.INSTANCE.getInstallReferrer());
            jsonObject.put("code", "0000");
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("directLoginFlag", "YES");
            jsonObject.put("notBindWalletFlag", "YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_LOGIN_NO_CODE, jsonObject.toString());
    }

    public void submitServiceFeedback(String type, String opinion) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opinion", opinion);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_FEED_BACK, jsonObject.toString());
    }

    //请求用户流程状态
    public void requestUserProcess() {
        request(UrlInfo_boom.gInstance().gJaee(), getRequestJson("", "").toString());
    }

    //请求用户流程状态
    public void requestUserProcess(String product,String token) {
        request(UrlInfo_boom.gInstance().gJaee(), getRequestJson("", "").toString());
    }

    //上传用户信息
    public void uploadInfo(String url, TreeMap<String, String> dataMap) {
        try {
            JSONObject jsonObject = getRequestJson();
            for (String k : dataMap.keySet()) {
                String key = Stringutil_boom.getSafeString(k);
                String value = Stringutil_boom.getSafeString(dataMap.get(k));
                jsonObject.put(key, value);
            }

            HttpManager_boom.Upload_Info_Url = url;
            String prefix = CountryInfo_boom.gInstance().gFront();
            if (!url.startsWith(prefix)) url = prefix + url;
            requestWithoutCountryPrefix(url, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //请求额度列表
    public void queryLoanLimit() {
        request(UrlInfo_boom.gInstance().gH8e7(), getRequestJson().toString());
    }

    //请求借款申请页信息/贷款详情
    public void requestLoanApplyDetail(String product, String token) {

        JSONObject jsonObject = getRequestJson(product, token);
        try {
            jsonObject.put("oldFlag", "YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        request(UrlInfo_boom.gInstance().gLrt0(), jsonObject.toString());
    }

    //发起借款申请
    public void loanApply(String product, String token) {
        request(UrlInfo_boom.gInstance().gA1ga(), getRequestJson(product, token).toString());
    }

    //获取还款信息
    public void getRepayDetail(String product, String token) {
        JSONObject jsonObject = getRequestJson(product, token);
        try {
            jsonObject.put("oldFlag", "YES");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(UrlInfo_boom.gInstance().gP3hr(), jsonObject.toString());
    }

    //获取还款H5（加纳、科特）
    public void orderRepayH5_gh_cl_vi(String product, String token) {
        request(UrlInfo_boom.gInstance().gAe2e(), getRequestJson(product, token).toString());
    }

    //获取还款H5（乌干达、肯尼亚）
    public void orderRepayH5_ug_ke(String product, String token) {
        request(UrlInfo_boom.gInstance().gQjy9(), getRequestJson(product, token).toString());
    }

    /**
     * 上传图片
     */
    public void uploadImage(String filePath_equitable) {
        if (Looper.myLooper() != Looper.getMainLooper())
            Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogShow());
        else HttpPresenter_boom.getInstance().progressBarDialogShow();
        try {
            if (!TextUtils.isEmpty(filePath_equitable)) {
                String fileSuffix_equitable = filePath_equitable.endsWith(".png") ? "image/png" : "image/jpg";
                final MediaType mediaType_equitable = MediaType.parse(fileSuffix_equitable);
                final File imageFile_equitable = new File(filePath_equitable);

                final String uplodUrl_equitable = CountryInfo_boom.gInstance().gBaseUrl() + CountryInfo_boom.gInstance().gFront() + Url_boom.PATH_UPLOAD_IMAGE_FILE;

                if (imageFile_equitable.isFile()) {
                    RequestBody imageBody = RequestBody.create(mediaType_equitable, imageFile_equitable);

                    RequestBody requestBody_equitable = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("image", imageFile_equitable.getName(), imageBody)
                            .build();

                    Request request_equitable = new Request.Builder()
                            .url(uplodUrl_equitable)
                            .post(requestBody_equitable)
                            .build();
                    Call call = mClient.newCall(request_equitable);
                    call.enqueue(callback);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取钱包列表（科特、喀麦隆）
    public void fetchBoundBankAccount(String product, String token) {
        request(UrlInfo_boom.gInstance().gCas5(), getRequestJson(product, token).toString());
    }

    //新增钱包（科特、喀麦隆）
    public void bindBankAccount(String walletMobile, String walletMobileConfirm, String walletChannel, String product, String token) {
        JSONObject jsonObject = getRequestJson(product, token);
        try {
            jsonObject.put("walletMobile", walletMobile);
            jsonObject.put("walletMobileConfirm", walletMobileConfirm);
            jsonObject.put("walletChannel", walletChannel);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(UrlInfo_boom.gInstance().gHner(), jsonObject.toString());
    }

    //删除钱包（科特、喀麦隆）
    public void deleteBoundBankAccount(String ids, String product, String token) {
        JSONObject jsonObject = getRequestJson(product, token);
        try {
            jsonObject.put("ids", ids);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(UrlInfo_boom.gInstance().gaUrf(), jsonObject.toString());
    }

    //获取评分弹窗信息
    public void fetchStarWindowConfig() {
        if (BaseLnActivity_boom.hasShowStarDalog) return;
        request(Url_boom.PATH_FETCH_STAR_WINDOW_CONFIG, getRequestJson().toString());
    }

    /**
     * 获取目标地区path
     */
    public void oceanpluszone(String tz) {

        Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogShow());

        String url = Url_boom.TimezoneUrl + "?p=" + Constant_boom.PRODUCT.toLowerCase() + "&tz=" + tz;
        Threadutils_boom.getInstance().runOnChildThread(() -> {
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = mClient.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    HttpPresenter_boom.getInstance().showToastOnUiThread("Request Fail");

                    Threadutils_boom.getInstance().runOnUiThread(() -> HttpPresenter_boom.getInstance().progressBarDialogDismiss());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String body = Objects.requireNonNull(response.body()).string();
                    Threadutils_boom.getInstance().runOnUiThread(() -> {
                        HttpPresenter_boom.getInstance().progressBarDialogDismiss();
                        try {
                            HttpPresenter_boom.getInstance().onTimezoneResponse(new JSONObject(body));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
        });
    }

    /**
     * 保存
     */
    public void saveData_A(String data) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("userInfo", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_SAVE_DATA, jsonObject.toString());
    }

    /**
     * 读取
     */
    public void getData_A() {
        request(Url_boom.PATH_GET_DATA, getRequestJson().toString());
    }

    public void getOtpCode(String mobile, String type) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("mobile", UserInfoHelper_boom.gInstance().gMobile());
            jsonObject.put("submitMobile", Stringutil_boom.getSafeString(mobile));
            jsonObject.put("sendType", Stringutil_boom.getSafeString(type));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_GET_CODE, jsonObject.toString());
    }

    public void checkMobile(String mobile, String type, String code) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("mobile", Stringutil_boom.getSafeString(mobile));
            jsonObject.put("submitMobile", Stringutil_boom.getSafeString(mobile));
            jsonObject.put("code", Stringutil_boom.getSafeString(code));
            jsonObject.put("checkType", Stringutil_boom.getSafeString(type));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_CHECK_MOBILE, jsonObject.toString());
    }

    /**
     * 获取TgBot Url
     */
    public void getTgBotUrl(String mobile) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("mobile", Stringutil_boom.getSafeString(mobile));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_GET_TGBOT_URL, jsonObject.toString());
    }

    public void fetchDropConfig() {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", "GET");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpPresenter_boom.getInstance().dropType = "GET";
        request(Url_boom.PATH_DELETE_USER_DATA_2, jsonObject.toString());
    }

    /**
     * 删除用户数据
     */
    public void deleteUserData() {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type", "DROP");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpPresenter_boom.getInstance().dropType = "DROP";
        request(Url_boom.PATH_DELETE_USER_DATA_2, jsonObject.toString());
    }


    /**
     * 复制主产品进件信息（贷超）
     */
    public void copyProcessInfo(String targetProduct) {
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("sourceProduct", Constant_boom.PRODUCT);
            jsonObject.put("targetProduct", targetProduct);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(Url_boom.PATH_COPY_PROCESS_INFO, jsonObject.toString());
    }

    /**
     * 获取产品列表（贷超）
     */
    public void queryProducts() {
        request(Url_boom.PATH_QUERY_PRODUCTS, getRequestJson().toString());
    }

    /**
     * 批量埋点
     */
    public void saveUserPointForBatch() {
        Threadutils_boom.getInstance().runEvenPointsThread(() -> {
            try {
                String front = CountryInfo_boom.gInstance().gFront();
                if (TextUtils.isEmpty(front)) return;

                JSONArray pointsArray = UserInfoHelper_boom.gInstance().gEvenPointsArray();
                UserInfoHelper_boom.gInstance().clearEvenPoints();
                if (pointsArray == null || pointsArray.length() == 0) return;
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("list", pointsArray);
                Request request = new Request.Builder()
                        .url(CountryInfo_boom.gInstance().gBaseUrl() + front + Url_boom.PATH_EVENT_POINT_FOR_BATCH)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .header("product", Constant_boom.PRODUCT)
                        .build();

                Call call = mClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {}

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {}
                });
            } catch (Exception e) {
                if (Constant_boom.Debug) e.printStackTrace();
            }
        });
    }

    /**
     * 获取设备数据上传状态
     */
    public void queryDeviceInfoType() {
        try {
            Request request = new Request.Builder()
                    .url(CountryInfo_boom.gInstance().gBaseUrl() + CountryInfo_boom.gInstance().gFront() + Url_boom.PATH_QUERY_DEVICE_INFO_TYPES)
                    .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), getRequestJson().toString()))
                    .header("product", Constant_boom.PRODUCT)
                    .build();

            Call call = mClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Demo demo = new Demo(BaseApplication_boom.getInstant_boom());
                    demo.upload(new String[]{"T1","T2","T3","T4","T5","T6","T7"});
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        String body = Objects.requireNonNull(response.body()).string();
                        JSONObject bodyJson = new JSONObject(body);
                        int code = Stringutil_boom.safeParseInt(bodyJson.optString("code"));
                        if (code != 0) return;
                        JSONObject obj = bodyJson.optJSONObject("obj");
                        if (obj==null) obj = bodyJson.optJSONObject("data");
                        if (obj==null) return;
                        JSONArray deviceInfoTypesJsonArray = obj.optJSONArray("deviceInfoTypes");
                        if (deviceInfoTypesJsonArray!=null){
                            String[] array = new String[deviceInfoTypesJsonArray.length()];
                            for (int i=0; i<array.length; i++){
                                array[i] = deviceInfoTypesJsonArray.optString(i);
                            }
                            Demo demo = new Demo(BaseApplication_boom.getInstant_boom());
                            demo.upload(array);
                        }
                    } catch (Exception e) {
                        if (Constant_boom.Debug) e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            if (Constant_boom.Debug) e.printStackTrace();
        }
    }

}
